package cc.momas.momall.search.message;

import java.io.IOException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import cc.momas.common.vo.SearchItem;
import cc.momas.momall.search.mapper.ItemMapper;

public class ItemAddMessageLinstener implements MessageListener {

	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private SolrServer solrServer;

	@Override
	public void onMessage(Message message) {
		try {
			System.out.println("触发监听器" + this.getClass());
			
			TextMessage msg = (TextMessage) message;
			String text = msg.getText();
			Long itemId = new Long(text);
			// 这个睡眠时间用于等待添加item的事务的提交,如果不等待有可能导致后续步骤查不到值
			Thread.sleep(500);
			// 根据商品id查询商品信息
			SearchItem searchItem = itemMapper.getItemById(itemId);
			// 创建一个文档对象
			SolrInputDocument document = new SolrInputDocument();
			// 向文档对象中添加域
			document.addField("id", searchItem.getId());
			document.addField("product_name", searchItem.getTitle());
			document.addField("product_sell_point", searchItem.getSell_point());
			document.addField("product_price", searchItem.getPrice());
			document.addField("product_picture", searchItem.getImage());
			document.addField("product_catalog_name", searchItem.getCategory_name());
			// 把文档写入索引库
			solrServer.add(document);
			// 提交
			solrServer.commit();
		} catch (NumberFormatException | JMSException | InterruptedException | SolrServerException | IOException e) {
			e.printStackTrace();
		}

	}

}
